package com.adhere.gateway.filter;

import com.adhere.common.constants.SecurityConstants;
import com.adhere.common.constants.SystemConstants;
import com.adhere.gateway.config.IgnoreWhiteProperties;
import com.adhere.gateway.config.JwtProperties;
import com.adhere.common.utils.JwtUtils;
import com.adhere.common.utils.ObjectUtils;
import com.adhere.common.utils.ServletUtils;
import com.adhere.common.utils.TypeConvertUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 验证请求的 token 是否合法
 *
 * @author WT
 * @date 2022/02/09 11:17:23
 */
@Slf4j
@Component
public class TokenFilter implements GlobalFilter, Ordered {

    /**
     * 排除过滤的 uri 地址，写在配置文件中
     */
    private final IgnoreWhiteProperties ignoreWhite;
    private final JwtProperties jwtProperties;
    private final RedisTemplate<String,Object> redisTemplate;

    public TokenFilter (IgnoreWhiteProperties ignoreWhite,
                       JwtProperties jwtProperties,
                       RedisTemplate<String,Object> redisTemplate) {
        this.ignoreWhite = ignoreWhite;
        this.jwtProperties = jwtProperties;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpRequest.Builder mutate = request.mutate();

        String url = request.getURI().getPath();

        // 跳过不需要验证的路径
        if (ObjectUtils.urlAntPathMatches(url, ignoreWhite.getWhites())) {
            return chain.filter(exchange);
        }

        String token = getToken(request);
        if (ObjectUtils.isEmpty(token)) {
            return unauthorizedResponse(exchange, "令牌不能为空");
        }

        Claims claims = JwtUtils.getClaimFromToken(token, jwtProperties.getSecret());
        if (claims == null) {
            return unauthorizedResponse(exchange, "令牌已过期或验证不正确！");
        }

        String userKey = TypeConvertUtils.objectToString(claims.get(SecurityConstants.USER_KEY));
        if (!redisTemplate.hasKey(userKey)) {
            return unauthorizedResponse(exchange, "登录状态已过期");
        }

        String userId = TypeConvertUtils.objectToString(claims.get(SecurityConstants.USER_ID));
        String loginName = TypeConvertUtils.objectToString(claims.get(SecurityConstants.LOGIN_NAME));
        if (ObjectUtils.isEmpty(userId) || ObjectUtils.isEmpty(loginName)) {
            log.error("[adhere-gateway - TokenFilter]: userId 或者 loginName 有一个为 null, userId = {}, loginName = {}", userId, loginName);
            return unauthorizedResponse(exchange, "令牌验证失败");
        }

        // 设置用户信息到请求
        addHeader(mutate, SecurityConstants.USER_KEY, userKey);
        addHeader(mutate, SecurityConstants.USER_ID, userId);
        addHeader(mutate, SecurityConstants.LOGIN_NAME, loginName);
        // 内部请求来源参数清除
//        removeHeader(mutate, SecurityConstants.FROM_SOURCE);
        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }

    private void addHeader(ServerHttpRequest.Builder mutate, String name, Object value) {
        if (value == null) {
            return;
        }
        String valueStr = value.toString();
        String valueEncode = ServletUtils.urlEncode(valueStr);
        mutate.header(name, valueEncode);
    }

    private void removeHeader(ServerHttpRequest.Builder mutate, String name) {
        mutate.headers(httpHeaders -> httpHeaders.remove(name)).build();
    }

    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, String msg) {
        log.error("[鉴权异常处理]请求路径:{}", exchange.getRequest().getPath());
        return ServletUtils.webFluxResponseWriter(exchange.getResponse(), msg, HttpStatus.UNAUTHORIZED.value());
    }

    /**
     * 获取请求token
     */
    private String getToken(ServerHttpRequest request) {
        String token = request.getHeaders().getFirst(SecurityConstants.TOKEN_AUTHORIZATION);
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (ObjectUtils.isNotEmpty(token) && token.startsWith(SecurityConstants.TOKEN_PREFIX)) {
            token = token.replaceFirst(SecurityConstants.TOKEN_PREFIX, SystemConstants.EMPTY_STR);
        }
        return token;
    }

    /**
     * the object with the lowest value has the highest priority
     * @return int
     */
    @Override
    public int getOrder() {
        return -200;
    }

}